<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="queryParams.productName" style="width:200px" placeholder="商品名称" clearable
            @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="需要积分" prop="points">
          <el-input v-model="queryParams.minPoints" style="width:150px" placeholder="最低值" clearable
            @keyup.enter="handleQuery()"></el-input>
          <span style="margin:0 10px">至</span>
          <el-input v-model="queryParams.maxPoints" style="width:150px" placeholder="最高值" clearable
            @keyup.enter="handleQuery()"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['sys:product:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button v-hasPerm="['sys:product:delete']" type="danger" :disabled="removeIds.length === 0"
          @click="handleDelete()">
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
        <el-button type="primary" icon="ShoppingCart" @click="openShoppingCardDrawer()">
          购物车
        </el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="pic" label="图片" prop="pic" min-width="100" align="center">
          <template #default="scope">
            <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[scope.row.pic]"
              style="width: 100px; height: 100px" :src="scope.row.pic" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column key="productName" label="商品名称" prop="productName" min-width="150" align="center" />
        <el-table-column key="points" label="需要积分" prop="points" min-width="150" align="center" />
        <el-table-column key="stock" label="库存" prop="stock" min-width="150" align="center" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button v-hasPerm="['sys:product:edit']" type="primary" size="small" link
              @click="handleOpenDialog(scope.row.id)">
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button v-hasPerm="['sys:product:delete']" type="danger" size="small" link
              @click="handleDelete(scope.row.id)">
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
            <!--加入购物车-->
            <el-button type="primary" size="small" link @click="addCart(scope.row)" v-if="userStore.judgeGuestUser()">
              <template #icon>
                <Plus />
              </template>
              加入购物车
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 商品管理表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="handleCloseDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">

        <el-form-item label="图片" prop="pic">
          <SingleImageUpload v-model="formData.pic" v-if="!formData.pic || formData.pic.trim() === ''" />
          <el-image v-else :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[formData.pic]"
            style="width: 100px; height: 80px" :src="formData.pic" fit="cover"></el-image>
        </el-form-item>

        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="formData.productName" placeholder="商品名称" />
        </el-form-item>

        <el-form-item label="需要积分" prop="points">
          <el-input v-model.number="formData.points" placeholder="需要积分" />
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input v-model="formData.stock" placeholder="库存" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog()">取消</el-button>
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!--购物车抽屉-->
  <el-drawer v-model="shoppingCartDrawer" title="购物车" @close="closeShoppingCardDrawer()">
    <el-space v-for="product in shoppingInfo.shoppingCart" :key="product.productId" style="
        width: 100%;
        border: #a9a9a9 1px solid;
        border-radius: 5px;
        padding: 0 5px;
        margin: 5px 0;
        display: flex;
      ">
      <!-- 图片预览 -->
      <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[product.pic]"
        style="width: 150px; height: 100px" :src="product.pic" fit="cover" />
      <div style="margin-left: 10px;width:100%;">
        <p>{{ product.productName }}</p>
        <el-input-number v-model="product.quantity" :min="1" :max="product.stock"
          @change="changeQuantity(product)"></el-input-number>
        <p>积分：{{ product.costPoints }} 积分</p>
      </div>
      <el-button type="danger" link style="margin:auto 20px" @click="removeCart(product)">移除</el-button>
    </el-space>
    <div style="display: flex;margin-top:20px;justify-content: space-between">
      <div>
        <p>合计：{{ shoppingInfo.totalPoints }} 积分</p>
      </div>
      <div>
        <el-button type="danger" @click="clearCart()">清空</el-button>
        <el-button type="primary" @click="toSettlement()" :disabled="shoppingInfo.shoppingCart.length == 0">
          去结算</el-button>
      </div>
    </div>
  </el-drawer>
  <!--订单信息弹框-->
  <el-dialog v-model="orderInfoDialog.visible" :title="orderInfoDialog.title">
    <el-form ref="shoppingInfoFormRef" :rules="shoppingInfoRules" :model="shoppingInfo" label-width="100px">
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="shoppingInfo.mobile" placeholder="手机号" />
      </el-form-item>
      <el-form-item label="收货地址" prop="address">
        <el-cascader size="large" :options="pcaTextArr" v-model="shoppingInfo.area"></el-cascader>
        <el-input v-model="shoppingInfo.address" placeholder="详细地址"
          style="margin-left: 10px; height: 40px; width: 300px"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="orderInfoDialog.visible = false">取消</el-button>
        <el-popconfirm title="是否确认支付" @confirm="goPay()" @cancel="cancelPay()">
          <template #reference>
            <el-button type="primary">立即支付</el-button>
          </template>
        </el-popconfirm>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({
  name: "Product",
  inheritAttrs: false,
});
import { reactive, ref, onMounted } from "vue";
import OrderAPI from "@/api/system/order";
import ProductAPI, { ProductPageVO, ProductForm, ProductPageQuery } from "@/api/system/product";
import { ElMessage, ElMessageBox } from "element-plus";
import { pcaTextArr } from "element-china-area-data";
import { useUserStore } from '@/store'

const userStore = useUserStore()

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ProductPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 商品管理表格数据
const pageData = ref<ProductPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 商品管理表单数据
const formData = reactive<ProductForm>({});

// 商品管理表单校验规则
const rules = reactive({
  id: [{ required: true, message: "请输入", trigger: "blur" }],
  productName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  points: [{ required: true, message: "请输入需要积分", trigger: "blur" }],
  stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
});

/** 查询商品管理 */
function handleQuery() {
  loading.value = true;
  ProductAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置商品管理查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.minPoints = undefined;
  queryParams.maxPoints = undefined;
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开商品管理弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改商品管理";
    ProductAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增商品管理";
  }
}

/** 提交商品管理表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ProductAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ProductAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭商品管理弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  // 重置所有表单数据
  Object.assign(formData, {
    id: undefined,
    pic: '',
    productName: '',
    points: '',
    stock: ''
  });
}

/** 删除商品管理 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ProductAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}



/**
 * 购物功能
 */
//购物车抽屉
const shoppingCartDrawer = ref(false)
const openShoppingCardDrawer = () => {
  shoppingCartDrawer.value = true
}
const closeShoppingCardDrawer = () => {
  shoppingCartDrawer.value = false
}
//购物车功能
const shoppingInfoFormRef = ref()
const shoppingInfoRules = reactive({
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  address: [
    {
      required: true,
      message: "请选择收货地址",
      validator: (rule: any, value: any, callback: any) => {
        if (shoppingInfo.area.length === 0 || shoppingInfo.address.trim() === '') {
          callback(new Error("请选择收货地址"))
        } else {
          callback()
        }
      }
    }
  ],
})
const shoppingInfo = reactive({
  mobile: '',
  area: [],//省市区数组
  address: '',
  totalPoints: 0,
  shoppingCart: [] as any
})
watch(shoppingInfo.shoppingCart, (newVal) => {
  //计算总积分
  shoppingInfo.totalPoints = 0
  newVal.forEach((item: any) => {
    shoppingInfo.totalPoints += Number(item.costPoints)
  })
})
//加入购物车
const addCart = (product: any) => {
  //判断购物车中是否已经有该商品
  const index = shoppingInfo.shoppingCart.findIndex((item: any) => item.productId === product.id)
  if (index === -1) {
    //如果购物车中没有该商品，则添加该商品
    shoppingInfo.shoppingCart.push({
      productId: product.id,
      pic: product.pic,
      productName: product.productName,
      points: product.points,//单价积分
      costPoints: product.points, //总计花费积分
      quantity: 1,
      stock: product.stock // 添加库存信息
    })
  } else {
    //如果购物车中已经有该商品，则数量加1
    if (shoppingInfo.shoppingCart[index].quantity < product.stock) {
      shoppingInfo.shoppingCart[index].quantity++
      shoppingInfo.shoppingCart[index].costPoints = shoppingInfo.shoppingCart[index].quantity * product.points
    } else {
      ElMessage.warning(`该商品库存仅剩 ${product.stock} 件`)
      return
    }
  }

  ElMessage.success("加入购物车成功")
}
//移出购物车
const removeCart = (product: any) => {
  console.log("移除", product)
  const index = shoppingInfo.shoppingCart.findIndex((item: any) => item.productId === product.productId)
  if (index === -1) {
    return
  }
  shoppingInfo.shoppingCart.splice(index, 1)
  ElMessage.success("移除购物车成功")
}
//增加减少商品数量
const changeQuantity = (product: any) => {
  const index = shoppingInfo.shoppingCart.findIndex((item: any) => item.productId === product.productId)
  if (index === -1) return

  // 验证数量合法性
  if (product.quantity < 1) {
    product.quantity = 1
    ElMessage.warning('商品数量不能小于1')
  } else if (product.quantity > product.stock) {
    product.quantity = product.stock
    ElMessage.warning(`该商品库存仅剩 ${product.stock} 件`)
  }

  // 更新总积分
  shoppingInfo.shoppingCart[index].quantity = product.quantity
  shoppingInfo.shoppingCart[index].costPoints = Number(shoppingInfo.shoppingCart[index].quantity * product.points).toFixed(2)
}
//清空购物车
const clearCart = () => {
  shoppingInfo.shoppingCart.splice(0, shoppingInfo.shoppingCart.length)
}
/**
 * 订单信息弹窗
 */
const orderInfoDialog = reactive({
  visible: false,
  title: '订单信息',
})
/**
 * 去结算
 */
const toSettlement = () => {
  orderInfoDialog.visible = true
}
/**
 * 取消支付
 */
const cancelPay = () => {
  OrderAPI.generateOrder(shoppingInfo)
    .then((data) => {
      ElNotification({
        title: '订单通知',
        message: '生成订单成功',
        type: 'success',
      })
      ElMessage.success('已取消支付')
    })
    .finally(() => {
      orderInfoDialog.visible = false
    })
}
/**
 * 去支付
 */
const goPay = () => {
  shoppingInfoFormRef.value?.validate((valid: any) => {
    if (valid) {
      OrderAPI.generateOrder(shoppingInfo)
        .then((data) => {
          ElNotification({
            title: '订单通知',
            message: '生成订单成功',
            type: 'success',
          });
          OrderAPI.settleOrder(data)
            .then(() => {
              ElMessage.success('支付成功');
              // 支付成功后清空购物车并关闭弹窗
              shoppingInfoFormRef.value?.resetFields();
              shoppingInfoFormRef.value?.clearValidate();
              shoppingInfo.shoppingCart = [];
              shoppingInfo.area = []
            })
            .finally(() => {
              shoppingCartDrawer.value = false;
              orderInfoDialog.visible = false;
              handleResetQuery();
            });
        })
        .finally(() => {
          shoppingCartDrawer.value = false;
          orderInfoDialog.visible = false;
          handleResetQuery();
        });
    }
  })

};
onMounted(() => {
  handleQuery();
});
</script>
<style socped>
.dialog-footer {
  text-align: center;
}
</style>